import { _decorator, Component, error, ImageAsset, Node, Rect, rect, resources, Sprite, SpriteComponent, SpriteFrame, UITransform, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Picture')
export class Picture extends Component {
    @property(SpriteComponent)
    pic:SpriteComponent = null; // 图片组件
    public init(pic_path:string, width:number, pos:Vec2, total_size:number) {
        let url : string = "picture/game";
        // let url : string = "picture/game/spriteFrame";
        resources.load(url, ImageAsset, (error:any, imageAsset) => {
            // 图片的原点坐标在左上角x=width,y=height
            // pos, x=width, y=height
            if (error) {
                console.log(error);
                return;
            }
            this.pic.spriteFrame = SpriteFrame.createWithImage(imageAsset);
            let pic_w = Math.round(imageAsset.width/total_size);
            let pic_h = Math.round(imageAsset.height/total_size);
            let picTf = this.pic.getComponent(UITransform)!; // 获取图片的UITransform组件
            picTf.width = width;
            picTf.height = width;
            let pic_x = pos.y*pic_w;
            let pic_y = imageAsset.height - (pos.x+1)*pic_h;
            // 计算图片显示区域
            // console.log(pos, pic_x, pic_y, pic_w, pic_h);
            this.pic.spriteFrame.rect = new Rect(pic_x, pic_y, pic_w, pic_h);
        });
    }
}